package com.watson;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.watson.fragment.HomeFragment;
import com.watson.fragment.UserFragment;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.mq.ReceiveMessageTask;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;
import com.watson.view.IndicatorProgressBar;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends BaseActivity {
    private long mExitTime = 0;//退出程序
    private Fragment[] mFragments;
    //当前Fragent的下标
    private int currentIndex;
    private RadioGroup tab_menu;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        statusbar4();
        tab_menu = findViewById(R.id.tab_menu);

        initViews();

        String id = SPUtils.get(mContext, "benT", "") + "";
        String insertTime = SPUtils.get(mContext, "benE", "") + "";
        String loginfo = SPUtils.get(mContext, "benS", "") + "";
        if (!StringUtils.isEmpty(id)) {
            insert_WMS_LoggerInfo(id, insertTime, loginfo);
        }

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                get_WMS_RefreshToken();
//            }
//        }, 2000);
        //TODO 版本更新
        get_WMS_Versions();
        Start();
    }

    //MQ调用
    private void Start() {
        // 发送
//        new SendMessageTask().execute("{\"type\":1,\"no\":\"9000003\",\"billno\":\"2322-99072900009\",\"msg\":\"2322-99072900009撤单\"}");
        // 接收
        new ReceiveMessageTask().execute();
    }

    private void insert_WMS_LoggerInfo(String id, String insertTime, String loginfo) {
        Map data = new HashMap();
//        data.put("id", loginfo);
//        data.put("insertTime", insertTime);
        data.put("loginfo", insertTime);
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().postData(CommonHttpConsts.insert_WMS_LoggerInfo, "insert_WMS_LoggerInfo")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(datStr)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        SPUtils.put(mContext, "benT", "");
                        SPUtils.put(mContext, "benE", "");
                        SPUtils.put(mContext, "benS", "");
                    }
                });
    }

    public static void get_WMS_RefreshToken() {
        HttpClient.getInstance().getData(CommonHttpConsts.get_WMS_RefreshToken, "get_WMS_RefreshToken")
                .params("token", SPUtils.get(MyApp.getContext(), "token", "") + "")
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            SPUtils.put(MyApp.getContext(), "token", info);//token码
                        } else {
                            ToastUtil.show(msg);
                        }
                    }
                });
    }

    private int isforcedupdate = 0;

    public void get_WMS_Versions() {
        HttpClient.getInstance().getData(CommonHttpConsts.get_WMS_Versions, "get_WMS_Versions")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .params("version", StringUtils.getVerName(mContext))
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info) && info.length() > 10) {
                            ArrayList<Map> dataMap = (ArrayList<Map>) JSON.parseArray(info, Map.class);
                            if (dataMap.size() > 0) {
                                downloadurl = dataMap.get(0).get("url") + "";
                                app_name = dataMap.get(0).get("name") + "";
                                tvContext.setText(dataMap.get(0).get("remark") + "");
                                String isfo = dataMap.get(0).get("isforcedupdate") + "";
                                if (!StringUtils.isEmpty(isfo)) {
                                    isforcedupdate = Integer.valueOf(isfo);
                                }
                                lyDialog.setVisibility(View.VISIBLE);
                                if (isforcedupdate == 1) {
                                    tvDialogCancel.setVisibility(View.GONE);
                                } else {
                                    tvDialogCancel.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                    }
                });
    }

    //系统升级
    private IndicatorProgressBar mProgress;
    private RelativeLayout rl_softu;
    private LinearLayout lyDialog;
    private TextView tvContext;
    private String destfiledir;
    private String downloadurl;
    private String app_name = "";
    private TextView tvDialogCancel, tvDialogConfirm;

    private void initViews() {
        mFragments = new Fragment[]{new HomeFragment(), new UserFragment()};
        //开启事务
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        //设置为默认界面 MainHomeFragment
        ft.add(R.id.frameLayout_main, mFragments[0]).commit();
        //RadioGroup选中事件监听 改变fragment
        tab_menu.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.bottom_btn_1:
                        setIndexSelected(0);
                        break;
                    case R.id.bottom_btn_2:
                        setIndexSelected(1);
                        break;
                }
            }
        });

        destfiledir = Environment.getExternalStorageDirectory().getPath();
        LogUtils.e("tag", "destfiledir:" + destfiledir);
//        FileHelper.createFile(mContext, apkPath, "");
        mProgress = findViewById(R.id.update_progress);
        rl_softu = findViewById(R.id.rl_softu);
        lyDialog = findViewById(R.id.lyDialog);
        tvContext = findViewById(R.id.tvContext);
        tvDialogCancel = findViewById(R.id.tvDialogCancel);
        tvDialogConfirm = findViewById(R.id.tvDialogConfirm);
        rl_softu.setVisibility(View.GONE);
        rl_softu.setOnClickListener(v -> {
        });
        lyDialog.setOnClickListener(v -> {
        });

        tvDialogCancel.setOnClickListener(v -> lyDialog.setVisibility(View.GONE));
        tvDialogConfirm.setOnClickListener(v -> {
            lyDialog.setVisibility(View.GONE);
            rl_softu.setVisibility(View.VISIBLE);
            downloadNewFile();
        });
    }

    private void downloadNewFile() {
        OkGo.<File>get(downloadurl).tag(this).execute(new FileCallback(destfiledir, app_name) {
            @Override
            public void onSuccess(Response<File> response) {
                String s = destfiledir + "/" + app_name;
                rl_softu.setVisibility(View.GONE);
                installApk(s);
            }


            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                LogUtils.e("TAG", "下载进度：" + (int) (progress.fraction * 100));
                mProgress.setProgress((int) (progress.fraction * 100));
            }

            @Override
            public void onError(Response<File> response) {
                super.onError(response);
                runOnUiThread(() -> {
                    rl_softu.setVisibility(View.GONE);
                    ToastUtil.show("网络中断，请稍后再试！");
                });
            }
        });
    }

    /**
     * 安装apk
     */
    public void installApk(String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            ToastUtil.show("更新失败！未找到安装包");
            return;
        }

        LogUtils.e("TAG", "开始执行安装: " + apkPath);
        File apkFile = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.e("TAG", "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.watson.fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            LogUtils.e("TAG", "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }


    //设置Fragment页面
    protected void setIndexSelected(int index) {
        if (currentIndex == index) {
            return;
        }
        //开启事务
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        //隐藏当前Fragment
        ft.hide(mFragments[currentIndex]);
        //判断Fragment是否已经添加
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.frameLayout_main, mFragments[index]).show(mFragments[index]);
        } else {
            //显示新的Fragment
            ft.show(mFragments[index]);
        }
        ft.commit();

        currentIndex = index;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                ScreenManager.getScreenManager().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}